#!/usr/local/bin/python
# -*- coding: utf-8 -*-

from threading import Timer
from time import sleep
from Weather import *
import LoadConfig
import Fetion
import time
import sys
import webapp2

def GetTimeString():
	return time.strftime("%y/%m/%d %H:%M:%S", time.localtime())
def PrintLog(message):
	return
	#print(message)
	#sys.stdout.flush()
	#sys.stderr.flush()
class Scheduler:
	def __init__(self, file_name, fetion):
		self.file_name=file_name
		self.schedules=[]
		self.message_sent_today=False
		self.fetion=fetion
		self.reloadSchedule()
	def reloadSchedule(self):
		self.schedules=[]
		try:
			file=open(self.file_name, 'r')
			for line in file:
				self.schedules.append( eval(line) )
			file.close()
		except IOError:
			return
	def processTasks(self):
		PrintLog('scheduling tasks...')
		for (name,city,prefix) in self.schedules:
			PrintLog('schedule (%s,%s,%s)'%(name,city,prefix))
			message=prefix+getWeather(city)
			self.sendMessage(name, message)
			sleep(10)
	def sendMessage(self, name, message):
#		PrintLog('sending to %s [%s]'%(name,message))
		self.fetion.sendMessage(name, message)

class MainPage(webapp2.RequestHandler):
        def post(self):
                config = LoadConfig.LoadConfig("config.ini")
                fetion  = Fetion.FetionClient(config['mobileno'],config['mobilepassword'])
                scheduler = Scheduler('schedules', fetion)
                scheduler.processTasks()
                self.response.headers['Content-Type'] = 'text/plain'
                self.response.write('running jobs...')

app = webapp2.WSGIApplication([('/send', MainPage)],
                              debug=True)



